package com.tsingteng.cosfun.http;

import android.text.TextUtils;

import com.tsingteng.cosfun.app.App;
import com.tsingteng.cosfun.utils.AppUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.SPUtils;
import com.tsingteng.cosfun.utils.SignUtil;
//import com.tsingteng.cosfun.utils.SignUtil;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 描述 :添加请求头,签名等信息
 * 创建人: 肖利.
 * 时间:2018/8/4
 * qq(872179966)
 */

public class RequestInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        Request.Builder builder = original.newBuilder();
        //添加请求头
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Cookie", SPUtils.init().getString("cookie"));
        Map<String,String> map = new HashMap<>();
         if (original.method().equals("POST")) {
            FormBody.Builder newFormBody = new FormBody.Builder();
            if (original.body() instanceof FormBody) {
                FormBody oidFormBody = (FormBody) original.body();
                for (int i = 0; i < oidFormBody.size(); i++) {
                    String key = oidFormBody.encodedName(i);
                    String value = oidFormBody.value(i);
                    if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
                        newFormBody.add(key, value);
                        map.put(key,value);
                    }
                }
            }
            //信息动态获取,前期是固定的
            map.put("gid", AppUtils.getGid());

            LogUtils.v("RequestInterceptor", "mobileId " + AppUtils.getMobileId());
            map.put("plat","2");
            LogUtils.v("LogonUtils.getProFildId()"+LogonUtils.getProFildId());
             if (LogonUtils.getProFildId()!= 0) {
                 map.put("profile_id",String.valueOf(LogonUtils.getProFildId()));
             }
             String sign = SignUtil.build().sign(map);
             //添加sign
             newFormBody.add("sign",sign);
             builder.method(original.method(), newFormBody.build());

            for (int i = 0; i < newFormBody.build().size(); i++) {
                LogUtils.i("RxReqResInterceptor", "request body " + newFormBody.build().encodedName(i) + " = " + URLDecoder.decode(newFormBody.build().encodedValue(i), "utf-8"));
            }
            LogUtils.i("RxReqResInterceptor", "request url " + URLDecoder.decode(original.url().toString(), "utf-8"));

        }
        return chain.proceed(builder.build());
    }

}
